//
//  BDScanViewController.m
//  BadBoy
//
//  Created by wen on 2017/7/6.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "BDShopPayViewController.h"

@interface BDScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property(strong,nonatomic)AVCaptureDevice* device;

@property(strong,nonatomic)AVCaptureDeviceInput* input;

@property(strong,nonatomic)AVCaptureMetadataOutput* output;

@property(strong,nonatomic)AVCaptureSession* session;

@property(strong,nonatomic)AVCaptureVideoPreviewLayer* preview;

@property(strong,nonatomic) UIImageView *animanlView;
@property(strong,nonatomic) UIView *saomiaokuang;
@property(strong,nonatomic) NSTimer *timer;

@end

@implementation BDScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Device
    self.device= [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    self.input= [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    self.output= [[AVCaptureMetadataOutput alloc] init];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    self.session= [[AVCaptureSession alloc] init];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    if([self.session canAddInput:self.input]){
        [self.session addInput:self.input];
    }
    if([self.session canAddOutput:self.output]){
        [self.session addOutput:self.output];
    }
    CGFloat side = 230;
    //条码类型AVMetadataObjectTypeQRCode
    self.output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode];
    [self.output setRectOfInterest:CGRectMake((kBDScreenHeight - side) / 2.0 / kBDScreenHeight, (kBDScreenWidth - side) / 2.0 / kBDScreenWidth, side / 1.0 / kBDScreenHeight, side / 1.0 / kBDScreenWidth)];//这个值原点在右上角，x和y互换
    
    // Preview
    self.preview=[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity=AVLayerVideoGravityResizeAspectFill;
    self.preview.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [self.session startRunning];
    
    self.saomiaokuang = [[UIView alloc] initWithFrame:CGRectMake(0, 0, side, side)];
    _saomiaokuang.center = self.view.center;
//    _saomiaokuang.layer.borderColor = [UIColor greenColor].CGColor;
//    _saomiaokuang.layer.borderWidth = 1;
    _saomiaokuang.clipsToBounds = YES;
    [self.view addSubview:_saomiaokuang];
    
    for (int i = 0; i < 4; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i / 2 * (side - 30), i % 2 * (side - 30), 30, 30)];
        imageView.contentMode = UIViewContentModeTopLeft;
        imageView.clipsToBounds = NO;
        imageView.image = [UIImage imageNamed:@"qr_bord"];
        CGAffineTransform transform= CGAffineTransformMakeRotation(-M_PI_2 * i);
        if (i == 2) {
            transform = CGAffineTransformMakeRotation(-M_PI_2 * 3);
        }else if (i == 3){
            transform = CGAffineTransformMakeRotation(-M_PI_2 * 2);
        }
        imageView.transform = transform;
        [_saomiaokuang addSubview:imageView];
    }
    
    self.animanlView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -30, side, 15)];
    _animanlView.image = [UIImage imageNamed:@"qr_line"];
    [_saomiaokuang addSubview:_animanlView];
    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    for (int i = 0; i < 4; i++) {
        UIView *bkView = [[UIView alloc] init];
        if (i < 2) {
            bkView.size = CGSizeMake(kBDScreenWidth, (kBDScreenHeight - side) / 2.0);
            if (i == 0) {
                bkView.top = 0;
            }else{
                bkView.bottom = kBDScreenHeight;
            }
        }else{
            bkView.size = CGSizeMake((kBDScreenWidth - side) / 2.0, side);
            bkView.centerY = self.view.height / 2.0;
            if (i == 2) {
                bkView.left = 0;
            }else{
                bkView.right = self.view.width;
            }
        }
        bkView.backgroundColor = [UIColor blackColor];
        bkView.alpha = 0.8;
        [self.view addSubview:bkView];
    }
    
    UILabel *alertLabel = [[UILabel alloc] init];
    alertLabel.text = ASLocalizedString(@"请将二维码放入框内，以便自动扫描");
    alertLabel.textColor = [UIColor whiteColor];
    alertLabel.font = [UIFont systemFontOfSize:16];
    alertLabel.size = CGSizeMake([alertLabel.text widthWithFont:alertLabel.font], 16);
    alertLabel.top = _saomiaokuang.bottom + 30;
    alertLabel.centerX = self.view.width / 2.0;
    [self.view addSubview:alertLabel];
    //
//    NSArray *iamgeArr = @[@"icon_pic.png",@"icon_flash.png",@"icon_flash_on.png"];
//    for (int i = 0; i < 2; i++) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.size = CGSizeMake(60, 60);
//        [button setBackgroundImage:[UIImage imageNamed:iamgeArr[i]] forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(bottomButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        button.tag = 500 + i;
//        button.bottom = SCREEN_HEIGHT - 50;
//        button.left = _saomiaokuang.left;
//        if (i == 1) {
//            button.right = _saomiaokuang.right;
//            [button setBackgroundImage:[UIImage imageNamed:iamgeArr[2]] forState:UIControlStateSelected];
//        }
//        [self.view addSubview:button];
//    }
    //
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 5, 25 ,25)];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backButton.centerY = kBDNavBarHeight /2.0 + kBDStatusBarHeight;
    [self.view addSubview:backButton];
    
    [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UILabel *titlelabel = [[UILabel alloc] init];
    titlelabel.font = [UIFont boldSystemFontOfSize:17];
    titlelabel.textColor = [UIColor whiteColor];
    titlelabel.text = ASLocalizedString(@"扫描二维码");
    [titlelabel sizeToFit];
    titlelabel.centerX = kBDScreenWidth / 2.0;
    titlelabel.centerY = backButton.centerY;
    [self.view addSubview:titlelabel];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [_session startRunning];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)timerAction:(NSTimer *)timer{
    self.animanlView.bottom = 0;
    [UIView animateWithDuration:1.5 animations:^{
        self.animanlView.top = self.saomiaokuang.height;
    }];
}

- (void)backButtonAction:(UIButton *)button{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)bottomButtonAction:(UIButton *)button{
    NSInteger index = button.tag % 100;
    if (index == 0) {
        //    NSLog(ASLocalizedString(@"从相册选择图片"));
    }else{
        //     NSLog(ASLocalizedString(@"开启闪光灯"));
        button.selected = !button.selected;
        //        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        //        AVCapturePhotoSettings
        //修改前必须先锁定
        [self.device lockForConfiguration:nil];
        //必须判定是否有闪光灯，否则如果没有闪光灯会崩溃
        if ([self.device hasFlash]) {
            
            if (self.device.torchMode == AVCaptureFlashModeOff) {
                self.device.torchMode = AVCaptureFlashModeOn;
            } else if (self.device.torchMode == AVCaptureFlashModeOn) {
                self.device.torchMode = AVCaptureFlashModeOff;
            }
        } else {
            
            //        NSLog(ASLocalizedString(@"设备不支持闪光灯"));
        }
        [self.device unlockForConfiguration];
        
        //        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        //        if (device.torchMode == AVCaptureTorchModeOff) {
        //            //Create an AV session
        //            AVCaptureSession * session = [[AVCaptureSession alloc]init];
        //
        //            // Create device input and add to current session
        //            AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        //            [session addInput:input];
        //
        //            // Create video output and add to current session
        //            AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc]init];
        //            [session addOutput:output];
        //
        //            // Start session configuration
        //            [session beginConfiguration];
        //            [device lockForConfiguration:nil];
        //
        //            // Set torch to on
        //            [device setTorchMode:AVCaptureTorchModeOn];
        //
        //            [device unlockForConfiguration];
        //            [session commitConfiguration];
        //
        //            // Start the session
        //            [session startRunning];
        //
        //            // Keep the session around
        //            self.session = session;
        //        }
    }
}

#pragma mark  ------------------AVCaptureMetadataOutputObjectsDelegate-------------------------
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    NSString*stringValue;
    
    if([metadataObjects count] >0){
        //   NSLog(ASLocalizedString(@"扫描到东西了"));
        //停止扫描  beboy://code/456784
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject* metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        // BDLog(@"%@", stringValue);
        if ([stringValue hasPrefix:@"beboy://shopPay/"]) {
            //商家付款
            NSString *goodsID = [[stringValue componentsSeparatedByString:@"/"] lastObject];
            BDShopPayViewController *shopPayVC = [[BDShopPayViewController alloc] init];
            shopPayVC.shop_id = goodsID;
            [self.navigationController pushViewController:shopPayVC animated:YES];
        }else if ([stringValue hasPrefix:@"beboy://user_id/"]) {
            NSString *userID = [[stringValue componentsSeparatedByString:@"/"] lastObject];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpToUserInfo" object:userID];
        }
        else{
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"未知的二维码")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    }
}

- (void)popSelf{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
